<template>
  <div class="role">
    <!-- 搜索框 -->
    <div class="search">
      <el-input
        placeholder="请输入角色名"
        clearable
        prefix-icon="el-icon-search"
        v-model="searchData"
      >
      </el-input>
      <el-button type="primary" icon="el-icon-search" @click="search"
        >搜索</el-button
      >
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="addDialogShow = true"
        >新增</el-button
      >
    </div>
    <!-- 添加角色 -->
    <div class="dialog2">
      <el-dialog
        @close="closeOuter(1)"
        title="新增角色"
        :visible.sync="addDialogShow"
        width="30%"
      >
        <el-form
          :model="addForm"
          :rules="rules"
          ref="addForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="addForm.roleName"
              clearable
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              type="textarea"
              v-model="addForm.description"
              clearable
              placeholder="请输入描述"
            ></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="addFn">确 认</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 编辑角色 -->
    <div class="dialog2">
      <el-dialog
        @close="closeOuter(2)"
        title="编辑角色"
        :visible.sync="dialogShow"
        width="30%"
      >
        <el-form
          :model="editForm"
          :rules="rules"
          ref="editForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="editForm.roleName"
              clearable
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              type="textarea"
              v-model="editForm.description"
              clearable
              placeholder="请输入描述"
            ></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogShow = false">取 消</el-button>
          <el-button type="primary" @click="editFn">确 认</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 给角色授权 菜单 -->
    <div class="dialog3">
      <el-dialog
        title="资源授权"
        :before-close="handleClose"
        :destroy-on-close="true"
        :visible.sync="dialogSet"
        width="50%"
      >
        <div class="left">
          <el-input
            placeholder="输入关键字进行过滤"
            clearable
            v-model="filterText"
          >
          </el-input>
          <el-tree
            node-key="id"
            show-checkbox
            default-expand-all
            class="filter-tree"
            :data="menuList"
            :default-checked-keys="own"
            :check-strictly="true"
            :expand-on-click-node="false"
            @node-click="change"
            @check="change"
            :props="defaultProps"
            :check-on-click-node="true"
            highlight-current
            :filter-node-method="filterNode"
            ref="tree"
          >
          </el-tree>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="setFn">保 存</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 表格数据 -->
    <div class="table">
      <el-table
        ref="isExpand"
        :data="roleData"
        v-loading="loading"
        border
        highlight-current-row
        height="calc(100%-10rem)"
        stripe
        style="width: 100%"
      >
        <template slot="empty">
          <el-empty description="暂无数据"></el-empty>
        </template>
        <el-table-column align="center" prop="roleName" label="角色名">
        </el-table-column>
        <el-table-column align="center" prop="description" label="描述">
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="openEditFn(scope.row)" size="small"
              >编辑</el-button
            >
            <el-button type="text" @click="openSetFn(scope.row)" size="small"
              >资源授权</el-button
            >
            <el-button type="text" size="small" @click="delFn(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="roleData.length !== 0"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 15, 20, 25, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getRolesApi,
  putRolesApi,
  addRolesApi,
  delRolesApi,
  getMenusApi,
  postRolesByMenusApi
} from "../../../../api/system/role";
export default {
  name: "Troles",
  data() {
    return {
      roleData: [],
      searchData: "",
      total: null,
      pageNum: 1,
      pageSize: 5,
      dialogShow: false,
      addDialogShow: false,
      dialogSet: false,
      editId: null,
      loading: false,
      menuList: [],
      own: [],
      filterText: "",
      row: [],
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 10, message: "请输入2-10位名称", trigger: "blur" }
        ],
        description: [
          { required: false, message: "请输入用户姓名", trigger: "blur" }
        ]
      },
      editForm: {
        roleName: "",
        description: ""
      },
      addForm: {
        roleName: "",
        description: ""
      }
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.pageSize = Number(sessionStorage.getItem("pageSize")) || 5;
    this.pageNum = Number(sessionStorage.getItem("pageNum")) || 1;
    this.getRoles(this.pageNum, this.pageSize, this.searchData);
  },
  destroyed() {
    sessionStorage.removeItem("pageNum");
    sessionStorage.removeItem("pageSize");
  },

  methods: {
    // 分页 pagesize
    handleSizeChange(val) {
      this.pageNum = 1;
      this.getRoles(this.pageNum, val, this.searchData);
      sessionStorage.setItem("pageSize", val);
      this.pageSize = val;
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    // 分页 pagenum
    handleCurrentChange(val) {
      this.getRoles(val, this.pageSize, this.searchData);
      sessionStorage.setItem("pageNum", val);
      this.pageNum = val;
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    // 条件查询
    search() {
      this.pageNum = 1;
      this.roleData = [];
      this.getRoles(this.pageNum, this.pageSize, this.searchData);
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    // 获取角色信息
    getRoles(pageNum, pageSize, roleName) {
      this.loading = true;
      getRolesApi(pageNum, pageSize, roleName).then(res => {
        this.total = res.data.total;
        if (res.data.rows.length == 0) {
          this.pageNum = this.pageNum - 1;
          if (this.pageNum > 0) {
            this.search();
          } else {
            this.roleData = res.data.rows;
            this.loading = false;
          }
          
        } else {
          this.loading = false;
          this.roleData = res.data.rows;
        }
      });
    },
    // 添加角色
    addFn() {
      addRolesApi(this.addForm)
        .then(res => {
          this.search();
          this.addDialogShow = false;
          this.$message.success("添加成功");
        })
        .catch(err => {
          this.$message.error("添加失败");
        });
    },

    // 关闭添加 对话框
    closeOuter(val) {
      if (val == 1) {
        // 移除校验结果和数据缓存
        this.$refs.addForm.resetFields();
      } else if (val == 2) {
        // 移除校验结果和数据缓存
        this.$refs.editForm.resetFields();
      }
    },
    // 打开修改角色信息窗口
    openEditFn(row) {
      console.log("编辑的数据", row);
    //   打开弹框传过去的row是Object对象类型，如果直接赋值的话，就变成了浅拷贝，复制的是地址，导致在表单中改变值的时候table中的数据也跟着改变，所以要进行深拷贝。
      this.dialogShow = true;
      this.editForm =Object.assign(this.editForm, row);
      this.editId = row.roleId;
    },
    // 确认修改角色信息
    editFn() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          putRolesApi(this.editId, this.editForm)
            .then(res => {
              this.dialogShow = false;
              this.search();
              this.$message.success("操作成功");
            })
            .catch(err => {
              this.$message.error("操作失败");
            });
        } else {
          this.$message.warning("格式有误，请重新填写");
        }
      });
    },
    // 删除角色信息
    delFn(e) {
      this.$confirm("确认删除此角色？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delRolesApi(e.roleId, this.token)
            .then(res => {
              this.search();
              this.$message.success("删除成功");
            })
            .catch(err => {
              console.log(err);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.warning("取消删除");
        });
    },
    change(e, d) {
      if (d.checkedKeys) {
        if (d.checkedKeys.indexOf(e.id) > -1) {
          d.checked = true;
        } else {
          d.checked = false;
        }
      }
      if (d.checked == true && e.children && e.children.length !== 0) {
        this.own.push(e.id);
        e.children.forEach(item => {
          this.own.push(item.id);
          if (item.children && item.children.length !== 0) {
            item.children.forEach(it => {
              this.own.push(it.id);
            });
          }
        });

        this.own = [...new Set(this.own)];
        this.$refs.tree.setCheckedKeys(this.own);
      } else if (d.checked == false && e.children && e.children.length !== 0) {
        if (this.own.indexOf(e.id) > 0) {
          this.own.splice(this.own.indexOf(e.id), 1);
        }
        e.children.forEach(item => {
          if (this.own.indexOf(item.id) > 0) {
            this.own.splice(this.own.indexOf(item.id), 1);
          }
          if (item.children && item.children.length !== 0) {
            item.children.forEach(it => {
              if (this.own.indexOf(it.id) > 0) {
                this.own.splice(this.own.indexOf(it.id), 1);
              }
            });
          }
        });
        this.own = [...new Set(this.own)];
        this.$refs.tree.setCheckedKeys(this.own);
      } else if (d.checked == false && e.children.length == 0) {
        if (this.own.indexOf(e.id) > 0) {
          this.own.splice(this.own.indexOf(e.id), 1);
        }
        this.own = [...new Set(this.own)];
        this.$refs.tree.setCheckedKeys(this.own);
      } else if (d.checked == true && e.children.length == 0) {
        this.own.push(e.id);
        this.own = [...new Set(this.own)];
        this.$refs.tree.setCheckedKeys(this.own);
      }
    },
    // 获取菜单信息
    getMenus() {
      const loading = this.$loading({
        target: document.querySelector(".dialog3 .el-dialog"),
        lock: true
      });
      getMenusApi(this.editId).then(res => {
        if (res.code == 200) {
        console.log('权限',res.data)
          this.menuList = res.data;
          this.menuList[0].disabled = true;
          this.own = [this.menuList[0].id];
          this.menuList.forEach(item => {
            if (item.own == true) {
              this.own.push(item.id);
            }
            if (item.children.length !== 0) {
              item.children.forEach(it => {
                if (it.own == true) {
                  this.own.push(it.id);
                }
                if (it.children.length !== 0) {
                  it.children.forEach(itt => {
                    if (itt.own == true) {
                      this.own.push(itt.id);
                    }
                  });
                }
              });
            }
          });
          console.log('权限',this.own);

          loading.close();
        }
      });
    },
    // 给角色分配菜单
    setFn() {
      const checkData = this.$refs.tree.getCheckedNodes();
      let arr = {
        menuIds: []
      };
      checkData.forEach(item => {
        // 菜单id
        arr.menuIds.push(item.id);
      });
      postRolesByMenusApi(this.editId, arr).then(res => {
        if (res.code == 200) {
          this.getMenus();
          this.$message.success("菜单分配成功");
        }
      });
    },
    // 打开资源授权
    openSetFn(row) {
      this.dialogSet = true;
      this.editId = row.roleId;
      this.getMenus();
    },
    // 取消
    handleClose() {
      this.dialogSet = false;
    },
    // 过滤筛选
    filterNode(value, data) {
      // console.log(value, data);
      if (!value) return true;
      return data.menuName.indexOf(value) !== -1;
    }
  }
};
</script>

<style lang="scss">
.role {
  padding-top: 15px;
  padding: 0 15px;
  height: calc(100vh - 100px);

  .search {
    margin-bottom: 15px;

    .el-input {
      width: 200px;
    }

    .el-button {
      width: 100px;
      margin-left: 15px;
    }
  }

  /deep/ .el-dialog__body {
    display: flex;

    .left {
      width: 50%;
    }

    .right {
      width: 50%;
    }
  }

  .table {
    height: 100%;

    .el-table {
      height: 70%;
    }

    .el-pagination {
      text-align: center;
      margin-top: 20px;
    }
  }

  .dialog3 {
    .el-dialog {
      .el-dialog__body {
        overflow: auto;
        height: 500px;
      }
    }
  }
}
</style>
